package com.ruoyi.system.utils;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.system.pojo.user.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;

/**
 * Description:
 *
 * @author JourWon
 * @date Created on 2025/5/13
 */
public class LoginUtils {

    /**
     * 验证验证码
     */
    public static void validateCaptcha(String inputCode, String redisCode) {
        if (StringUtils.isEmpty(inputCode)) {
            throw new ServiceException("验证码不能为空");
        }
        if (!inputCode.equalsIgnoreCase(redisCode)) {
            throw new ServiceException("验证码错误");
        }
    }

    /**
     * 验证用户状态
     */
    public static void validateUserStatus(User user) {
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        if ("1".equals(user.getStatus())) {
            throw new ServiceException("账号已停用");
        }
    }

    /**
     * 验证MD5密码
     * @param inputPwd 用户输入的原始密码
     * @param dbPwd 数据库中存储的MD5值
     * @throws ServiceException 密码不匹配时抛出
     */
    public static void validatePassword(String inputPwd, String dbPwd) {
        if (StringUtils.isEmpty(inputPwd) || StringUtils.isEmpty(dbPwd)) {
            throw new ServiceException("密码不能为空");
        }
        // 标准化数据库存储的MD5值
        String normalizedDbPwd = dbPwd.trim().toUpperCase();

        // 生成输入密码的MD5
        String hashedInput = DigestUtils.md5Hex(inputPwd.trim()).toUpperCase();

        if (!MessageDigest.isEqual(hashedInput.getBytes(), normalizedDbPwd.getBytes())) {
            throw new ServiceException("密码错误");
        }
    }

    /**
     * 生成MD5
     * @param password
     * @return
     */
    public static String generateMd5UpperCase (String password) {
        return DigestUtils.md5Hex(password.trim()).toUpperCase();
    }
}
